# -*- coding: utf-8 -*-
from tkinter.messagebox import showinfo
# python setup.py py2exe
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.select import Select
import time
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
import timeout_decorator
isdo = 0
zan_count = 0
zhuanfa_count = 0
liuyan_count = 0
zan_max = ''
zhuanfa_max = 500
liuyan_max = 500
isscroll = 0
willdo = 0
nownum = 0
cn_liuyan = "精彩拍摄"
en_liuyan = "Wonderful shooting"
login_no = '13816146456'
login_pw = "hjy11911xx"
from tkinter import *
from tkinter import ttk
from wincener import center


def contain_zh(s):
    for c in s:
        if not ('\u4e00' <= c <= '\u9fa5'):
            return False
    return True


# driver = webdriver.Chrome(executable_path='chromedriver.exe')

errlist = []
succlist = []

def is_element_exist(css):
    s = driver.find_elements_by_css_selector(css_selector=css)
    if len(s) == 0:
        print ("元素未找到:%s"%css)
        return False
    elif len(s) == 1:
        return True
    else:
        print ("找到%s个元素：%s"%(len(s),css))
        return False
opline=''


def time_limit(interval):
    def wraps(func):
        def time_out():
            raise RuntimeError()

        def deco(*args, **kwargs):
            timer = threading.Timer(interval, time_out)
            timer.start()
            res = func(*args, **kwargs)
            timer.cancel()
            return res

        return deco

    return wraps
# @time_limit(20)
def getdata(lines,linelist, driver):
    print('1212')
    try:
        print('aaa')
        sc = driver.find_elements_by_class_name('v_btn_cre')
        print('bbb')#v_btn_cre
        if len(sc) > 0:
            print('删除之')
            driver.find_element_by_class_name('v_btn_cre').click()
        else:
            print('无删除按钮，跳转添加页面')
        print('ccc')
        driver.get('https://www.daimaru-matsuzakaya.jp/CreditCard')
        driver.maximize_window()
        mychose = numberChosen.get()
        print('mychose', mychose)
        S = Select(driver.find_element_by_name('CARD_BRAND_CD')).select_by_visible_text(mychose)
        # 找到输入框并输入查询内容
        elem = driver.find_element_by_id("off_cardNo01")
        elem.send_keys(linelist[0][:4])
        driver.execute_script("ecValidateDataCard(arguments[0]);", "off_cardNo01")
        elem1 = driver.find_element_by_id("off_cardNo02")
        elem1.send_keys(linelist[0][4:8])
        driver.execute_script("ecValidateDataCard(arguments[0]);", "off_cardNo02")
        elem2 = driver.find_element_by_id("off_cardNo03")
        elem2.send_keys(linelist[0][8:12])
        driver.execute_script("ecValidateDataCard(arguments[0]);", "off_cardNo03")
        elem3 = driver.find_element_by_id("off_cardNo04")
        elem3.send_keys(linelist[0][12:16])
        driver.execute_script("ecValidateDataCard(arguments[0]);", "off_cardNo04")
        # 年月选择 LIMIT_MONTH LIMIT_YEAR
        S1 = Select(driver.find_element_by_name('LIMIT_MONTH')).select_by_visible_text(linelist[1])
        S2 = Select(driver.find_element_by_name('LIMIT_YEAR')).select_by_value(linelist[2].strip())
        print('选择填写完成，休息两秒钟 提交')

        # errspan = driver.find_element_by_class_name('tb-font-error')
        # print('errspan',errspan)
        # time.sleep(10)
        # 提交表单 //*[@id="EC_change"]/form/div[1]/a
        # LeftMenu = driver.find_element_by_class_name("cardAddLink")
        # ActionChains(driver).move_to_element(LeftMenu).perform()
        # # wait =  WebDriverWait(driver, 60);
        # # wait.until(EC.elementToBeClickable(LeftMenu))
        # LeftMenu.click()
        # 屏蔽提交
        # comment_icon = driver.find_element_by_class_name("cardAddLink").send_keys(Keys.ENTER)
        # print('comment_icon',comment_icon)
        # 更新提交方式
        sc = driver.find_elements_by_xpath('// *[ @ id = "EC_change"] / form / div[1] / a / img')
        if len(sc) > 0:
            print('提交')
            driver.find_element_by_xpath('// *[ @ id = "EC_change"] / form / div[1] / a / img').click()
        else:
            print('无提交按钮')
        # driver.find_element_by_xpath('// *[ @ id = "EC_change"] / form / div[1] / a / img').click()
        time.sleep(3)
        # errspan = driver.find_element_by_class_name('tb-font-error')
        errspan = driver.find_elements_by_class_name('tb-font-error')
        sc = driver.find_elements_by_class_name('v_btn_cre')
        print('1errspan', len(errspan), 'sc', len(sc))
        if len(errspan) > 0 and len(sc) == 0:
            print('失败记录')
            errlist.append(lines)
        else:
            print('成功，然后删除之')
            succlist.append(lines)
            driver.find_element_by_class_name('v_btn_cre').click()
            # // *[ @ id = "EC_pass"] / table / tbody / tr[2] / td[5] / a / img
    except Exception as e:
        print('异常了继续', e)
        if lines not in succlist and lines not in errlist:
            opline = lines
    # continue
    # 成功了重新进入
    # driver.get('https://www.daimaru-matsuzakaya.jp/CreditCard')
    # print(44444, 'driver', driver)
# driver = webdriver.Firefox()
def mylogin():
    global driver, login_no, login_pw,errlist,succlist,opline
    mycook = ent1.get()#'YSPCD=dmz; YSITEID=4; FormAssist_1tag=view; _ga=GA1.2.1551842280.1557730272; _gid=GA1.2.1798314663.1557730272; __ulfpc=201905131451155085; _fbp=fb.1.1557730279595.781182294; _ga=GA1.2.233470906.1557562204; _gid=GA1.2.1137660141.1557562204; __bvr_s1d=17hL7tDaGsN5wKTlpoNm4Eq9WlJbpM; __sna_s1d=17hL7tDaGsN5wKTlpoNm4Eq9WlJbpM; __ulfpc=201905111610074785; _fbp=fb.1.1557562212410.1829590691; companyec_visitor=mzwAufJy65OyGmWuiaUNpmWs1Q15JvckHaF6oCZPtuPAf3D8M5JbhtPhTRPZyTPnQOTlpIbCvmPL0Mbk2oRymqp21gHvhnrd2UVyGhGYxDyKeZo7kMniHov5rgVTHY8GJk6MD55ZTsgExI4OHbbKLVYydStdzoBmvQmqogOkJoHEi2kNFr9mp9d6Px7uSdb3OtHWOBxtnwBBdPxDk0LlHdbs8qTwSBA53iC3S3qjJcHsm3y3Kz8Y7ukLZWEKebln15Xs7pmH4EXieC7snKpybQLJ4SJ8dLnBEjTSyU8PuwCB; __bvr_customer={%22associated%22:true}; CI=b87a8e28fc97c21aae168aea62c7d204; FormAssist_cookie=jfr/20181109171257/20190512/085449-482; __bvr_session_activity={%22cart%22:true}; company_context=0.0.302.0:; _dc_gtm_UA-110157683-8=1; ALI=lplfZAEqjA-nl7y5gn!ynLmT%3dOzST_$MAmCC$__bh0sXb2HEUM; SI=9N0oHjB2hAr2j929qx6L44MHBtZh1YpTuxGVlJP0dm1EDGT3iR; T=qM1M26u7q83f42YjRgfT48mZcB3l7H77UMbe20tAtsm7756p78; _dc_gtm_UA-7119489-1=1; companyec_session=WlBamah64Z3miH2LT4t8S5SPbWgHjYqUSYATcsByBwWemg9V64F67NJYUQrdClSs6q4Qon38YeUXkFFQx3aZ1pzTOSgks1zGlSNfdAa62cYPogQmUNjuegcDq7L3GldlNgSP2YMPzXDKyQzN67gLL2KVI4pYtD6RNEE9WHJHUHPJkDmMmTLGlrE0QhTwv4xqztxpmsWsah8hP7n5UPZWO28uPTAGlk69r3OWnmOj8hDsVLwSRBzYzAvhF4eHag4a58QNPq9suUugNhRstUzIU7gHYKdxkjcwVXff9h8O0OsO; JSESSIONID=0000CLM1OZ4f8ivUypZ2STfEmHd:1bt4i6vtn; CSI=7NEWGmwtPlh!BVlhluVSFCn:keVj4kp*STVA8ICgQdmHz3jfM_; SCSI=4677d0669fedfbe5a8cf3c81d9c857a7766bb8aac735b83a366309143d77e482; DSCSI=94ef8651-1a36-41b8-826f-4376b71e9f41; BUI=hdSb9!U$XbUVaYll69tTQu6jevi3NvFdP%3dxJSlshD0UdP1lSbX'

    # {"VISAカード":'dmo03', "マスターカード", "JCBカード", "アメックスカード"}
    # return True
    # options = webdriver.ChromeOptions()
    # 添加保持登录的数据路径：安装目录一般在C:\Users\黄\AppData\Local\Google\Chrome\User Data
    # options.add_argument(r"user-data-dir=C:\Users\guoff\AppData\Local\Google\Chrome\User Data")
    # options.add_argument(
    #     'Accept                   ="text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"')
    # options.add_argument('Accept-Encoding          ="gzip, deflate, br"')
    # options.add_argument('Accept-Language          ="zh-CN,zh;q=0.9,en;q=0.8"')
    # options.add_argument('Cache-Control            ="max-age=0"')
    # options.add_argument('Connection               ="keep-alive"')
    # options.add_argument('Content-Length           ="468"')
    # options.add_argument('Content-Type             ="application/x-www-form-urlencoded"')
    # options.add_argument('Cookie="_ga=GA1.2.233470906.1557562204; _gid=GA1.2.1137660141.1557562204; __bvr_s1d=17hL7tDaGsN5wKTlpoNm4Eq9WlJbpM; __sna_s1d=17hL7tDaGsN5wKTlpoNm4Eq9WlJbpM; __ulfpc=201905111610074785; _fbp=fb.1.1557562212410.1829590691; companyec_visitor=mzwAufJy65OyGmWuiaUNpmWs1Q15JvckHaF6oCZPtuPAf3D8M5JbhtPhTRPZyTPnQOTlpIbCvmPL0Mbk2oRymqp21gHvhnrd2UVyGhGYxDyKeZo7kMniHov5rgVTHY8GJk6MD55ZTsgExI4OHbbKLVYydStdzoBmvQmqogOkJoHEi2kNFr9mp9d6Px7uSdb3OtHWOBxtnwBBdPxDk0LlHdbs8qTwSBA53iC3S3qjJcHsm3y3Kz8Y7ukLZWEKebln15Xs7pmH4EXieC7snKpybQLJ4SJ8dLnBEjTSyU8PuwCB; YSPCD=dmz; YSITEID=4; FormAssist_1tag=view; FormAssist_cookie=jfr/20181109171257/20190511/171105-898; __bvr_customer={%22associated%22:true}; __bvr_session_activity={%22cart%22:true}; companyec_session=jpPgYQvU93pVAT2cEu4RBWdyFk9IvTW8Q8Q3opRo5uoOirAtQHNXKNHHAcaRYrCEMc1Eqaby9iFetnYRXzUsl6mp4oSUn84Qy0I1iksq2jdv9EnKLmePtDF2E1U1N5EzgBTthsc5ZaQXJJwqSIXWfhtdrFP4dBtaOUBYc1d8tSFBCe475jMufpevH9UgufxwYbX29BDipqK9NGfGPPes4iu0UAxCbmZVXNPAyUThhVgMLQtrSgxndcbUh3sytyBVv2nz7cQCzJwpQ8ZiTQWGlcBmoFIp7QNd14CC7Vj5nTV8; company_context=1.0.302.0:; JSESSIONID=0000a9oXc90MwxiJAyLP6W2UOuJ:1bt4hvbfo; CSI=xsVWkhQUDH6sW$zmKX6y2V7t41AgFiwjpsV5%3dL_CNBUpKoPWB:; SCSI=26a71a380cbc62545bc9a0845dfe87e9a29fedc284398147814f59d9d11661c5; DSCSI=fb074d8b-3f57-462b-88be-858f820054a2; ALI=xsVWkhQUDH6sW$zmKX6y2V7t41AgFiwjpsV5%3dL_CNBUpKoPWB:; CI=b87a8e28fc97c21aae168aea62c7d204; SI=3y65uv39lrrfuNiLbqLcH6HVw79c48nf9AJ27zIF5k0Y91619f; T=iiK5s9oEm00H5c79P9nP7kM4KnsFE7szv8OY2LP89y7L1omJaj; BUI=uS4:6FcWQX@Wu3-Mss@Q6ml@HG*5*MW0luZu!qs6$*lT9LXwK_"')
    # options.add_argument('Host                     ="www.daimaru-matsuzakaya.jp"')
    # options.add_argument('Origin                   ="https://www.daimaru-matsuzakaya.jp"')
    # options.add_argument('Referer                  ="https://www.daimaru-matsuzakaya.jp/CreditCardAdd"')
    # options.add_argument('Upgrade-Insecure-Requests="1"')
    # options.add_argument(
    #     'User-Agent               ="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"')

    driver = webdriver.Chrome(executable_path='chromedriver.exe')
    #executable_path='chromedriver.exe',
    driver.get('https://www.daimaru-matsuzakaya.jp/CreditCard')
    print(22222, 'driver', driver)

    driver.implicitly_wait(10)  # 隐性等待
    cooklist = mycook.split(';')
    for cook in cooklist:
        clist = cook.split('=')
        cdict = {"name": clist[0], "value": clist[1]}
        print(cdict)
        driver.add_cookie(cookie_dict={"name": clist[0].strip(), "value": clist[1].strip()})
    # driver.add_cookie(cookie_dict={"name": "YSPCD", "value": "dmz"})
    # driver.add_cookie(cookie_dict={"name": "YSITEID", "value": "4"})
    # driver.add_cookie(cookie_dict={"name": "FormAssist_1tag", "value": "view"})
    # driver.add_cookie(cookie_dict={"name": "_ga", "value": "GA1.2.430707676.1557625578"})
    # driver.add_cookie(cookie_dict={"name": "_gid", "value": "GA1.2.332915399.1557625578"})
    # driver.add_cookie(cookie_dict={"name": "FormAssist_cookie", "value": "jfr/20181109171257/20190512/104615-862"})
    # driver.add_cookie(cookie_dict={"name": "__bvr_s1d", "value": "jf1L5Y1TTpMIGQRntKgoxbRXXwJdvA"})
    # driver.add_cookie(cookie_dict={"name": "__ulfpc", "value": "201905120946207997"})
    # driver.add_cookie(cookie_dict={"name": "companyec_visitor",
    #                                "value": "cqSw5tXvNcfNEgh9d9HbCyhhwtjtx3yoKTnEADzdpKRojJfuKZl9puYuB2gcYIosZZ6QANbErx3CIbDZILvouuAB5rSnaDwNAL70uEUD9WBpSJZdYzlOG28uv2ig3daB4rrnkGq7JUvDJ9othdQcGBiH9NxBGZpDaEYrYaDXKd0aNNSnjewwsOfrvZOJNs1BgqpCTCgZqCqkLfs8TlN6GWPWk38MyF4AMR7XVG0phFcmVyGPJZOW26izzzcZlD5swIC1dcw6i0aGf20Iw06FjDazwr9XIhyQ2G3q60xLJKpm"})
    # driver.add_cookie(cookie_dict={"name": "companyec_session",
    #                                "value": "B4PX4vSnxGG7upzN8bvE7ewR9noHzAG8ro1kRv7QSpKp8pouLATNng6CFTtn7re7MhqarfiuKPb3XhGYamjfClNZcKVL8MPvgvcaGhTpc136IlwrvP3ggXYSMw5WuuS6jBJAV1aV9eoc7tDGjmEGZ9YYpqvuqvwZTKUYzq3DG7wAdXywhONMLKhWCzKy05kiIzyMDE0F0TlDZn7zI21EQRto1s2e3twQp8XE99ghbD5jriabG12ZhVIrbUbzDPP49iVGhbS1RkGdsY9feE1b9URvM4CshOuT1QVUQC6MU0B1"})
    # driver.add_cookie(cookie_dict={"name": "_fbp", "value": "fb.1.1557625583902.1578749174"})
    # driver.add_cookie(cookie_dict={"name": "company_context", "value": "1.0.302.0:"})
    # driver.add_cookie(cookie_dict={"name": "JSESSIONID", "value": "00001C0eCG8V68_TMOBRXHkPOhC:1bt4hvbfo"})
    # driver.add_cookie(cookie_dict={"name": "CSI", "value": "ZE9QL9QGlT6uf600cNAd1zPxjwP5bGfeLqjW-1oiC9Cnn*m_2p"})
    # driver.add_cookie(
    #     cookie_dict={"name": "SCSI", "value": "150c2d425cce1ce81eeb6131ebae8b78dffa1b6d9cdfccce0d56f8622c30484d"})
    # driver.add_cookie(cookie_dict={"name": "DSCSI", "value": "4724754d-b8d0-4909-b5c4-dc2f452019a3"})
    # driver.add_cookie(cookie_dict={"name": "ALI", "value": "ZE9QL9QGlT6uf600cNAd1zPxjwP5bGfeLqjW-1oiC9Cnn*m_2p"})
    # driver.add_cookie(cookie_dict={"name": "CI", "value": "b87a8e28fc97c21aae168aea62c7d204"})
    # driver.add_cookie(cookie_dict={"name": "SI", "value": "6sX4Hmc5t056qem7c9COFbaB8P0t20x40Tr6Lo2Y8nWP5H6Yz8"})
    # driver.add_cookie(cookie_dict={"name": "T", "value": "CYPsyA8beCuDTr5J8uI47ToLqFRtNLp7MUE9MT8Gdh5R5TMHf7"})
    # driver.add_cookie(cookie_dict={"name": "BUI", "value": "Xwa@bsdH4k@M3uFmyWGHA*A$47OMU2EvTsyX_OWUl6ZFUhuTFi"})
    # driver.add_cookie(cookie_dict={"name": "__sna_s1d", "value": "jf1L5Y1TTpMIGQRntKgoxbRXXwJdvA"})
    print(33333, 'driver', driver)
    print(11111, 'driver', driver)

    # driver.find_element_by_css_selector("a.login").click()
    # # driver.maximize_window()  #将浏览器最大化显示
    # time.sleep(3)
    # driver.find_element_by_id("userName").send_keys(login_no)
    # driver.find_element_by_id("password").send_keys(login_pw)
    # driver.find_element_by_id("subButton").click()
    # time.sleep(1)
    # driver.find_element_by_css_selector("li._subscribeTab").click()
    # time.sleep(5)
    # driver.find_element_by_css_selector("a.v2_new_fav").click()
    #提交逻辑
    # 选项确定 dmo11
    # 填写卡号，填写有效期，提交
    # time.sleep(10)
    filename = 'inputdata.txt'  # txt文件和当前脚本在同一目录下，所以不用写具体路径
    ii=0
    with open(filename, 'r') as file_to_read:
        # opline = ''
        while True:
            if opline!='':
                lines = opline
            else:
                lines = file_to_read.readline()  # 整行读取数据
                opline = ''
            ii=ii+1 #or ii>5
            if not lines :
                break
                pass

            linelist = lines.split('|')
            print('linelist',linelist)



            # @timeout(10)

            # time.sleep(1)
            try:
                getdata(lines,linelist,driver)
            except Exception as e:
                print('异常了继续', e)
                if lines not in succlist and lines not in errlist:
                    opline = lines

    # ActionChains(driver).moveToElement(comment_icon).build().perform()
    # driver.execute_script("arguments[0].scrollIntoView();", comment_icon)
    # ActionChainsDriver = ActionChains(driver).click(comment_icon)
    print('查询操作完毕！errlist',errlist)
    print('查询操作完毕！succlist', succlist)
    sav()

    # time.sleep(10)
    # S = Select(driver.find_element_by_name('CARD_BRAND_CD')).select_by_value('dmo11')
    # # 找到输入框并输入查询内容
    # elem = driver.find_element_by_id("off_cardNo01")
    # elem.send_keys("1212")
    # driver.execute_script("ecValidateDataCard(arguments[0]);", "off_cardNo01")
    #
    # elem1 = driver.find_element_by_id("off_cardNo02")
    # elem1.send_keys("3121")
    # driver.execute_script("ecValidateDataCard(arguments[0]);", "off_cardNo02")
    # elem2 = driver.find_element_by_id("off_cardNo03")
    # elem2.send_keys("2421")
    # driver.execute_script("ecValidateDataCard(arguments[0]);", "off_cardNo03")
    # elem3 = driver.find_element_by_id("off_cardNo04")
    # elem3.send_keys("3333")
    # driver.execute_script("ecValidateDataCard(arguments[0]);", "off_cardNo04")
    # # 年月选择 LIMIT_MONTH LIMIT_YEAR
    # S1 = Select(driver.find_element_by_name('LIMIT_MONTH')).select_by_visible_text('01')
    # S2 = Select(driver.find_element_by_name('LIMIT_YEAR')).select_by_visible_text('21')
    # print('选择填写完成，休息两秒钟 提交')
    # time.sleep(2)
    # # 提交表单 //*[@id="EC_change"]/form/div[1]/a
    # # LeftMenu = driver.find_element_by_class_name("cardAddLink")
    # # ActionChains(driver).move_to_element(LeftMenu).perform()
    # # # wait =  WebDriverWait(driver, 60);
    # # # wait.until(EC.elementToBeClickable(LeftMenu))
    # # LeftMenu.click()
    # comment_icon = driver.find_element_by_class_name("cardAddLink").send_keys(Keys.ENTER)
    # print('二次完毕')
    # print('查询操作完毕！',ActionChainsDriver)
    # ActionChainsDriver.perform()

def sav():
    global succlist,errlist
    datetimenowTime = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')  # 现在
    # begin_date = datetime.datetime.strptime(datetimenowTime, "%Y-%m-%d%H:%M:%S")
    filename = "succ" + datetimenowTime + ".txt"
    badfilename = "bad" + datetimenowTime + ".txt"
    f1 = open('exp/' + filename, 'w')
    for a in succlist:
        f1.write(a)
    f1.close()
    f1 = open('exp/' + badfilename, 'w')
    for a in errlist:
        f1.write(a)
    f1.close()
    showinfo('Yes', '数据导出完毕')

def openurl():
    import webbrowser
    webbrowser.open("http://guofeifei.com/article/2019/5/13/989.html")
    # global driver, login_no, login_pw
    # # options = webdriver.ChromeOptions()
    # # # 添加保持登录的数据路径：安装目录一般在C:\Users\黄\AppData\Local\Google\Chrome\User Data
    # # options.add_argument(r"user-data-dir=C:\Users\guoff\AppData\Local\Google\Chrome\User Data")
    # # options.add_argument(
    # #     'Accept                   ="text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"')
    # # options.add_argument('Accept-Encoding          ="gzip, deflate, br"')
    # # options.add_argument('Accept-Language          ="zh-CN,zh;q=0.9,en;q=0.8"')
    # # options.add_argument('Cache-Control            ="max-age=0"')
    # # options.add_argument('Connection               ="keep-alive"')
    # # options.add_argument('Content-Length           ="468"')
    # # options.add_argument('Content-Type             ="application/x-www-form-urlencoded"')
    # # options.add_argument('Cookie="_ga=GA1.2.233470906.1557562204; _gid=GA1.2.1137660141.1557562204; __bvr_s1d=17hL7tDaGsN5wKTlpoNm4Eq9WlJbpM; __sna_s1d=17hL7tDaGsN5wKTlpoNm4Eq9WlJbpM; __ulfpc=201905111610074785; _fbp=fb.1.1557562212410.1829590691; companyec_visitor=mzwAufJy65OyGmWuiaUNpmWs1Q15JvckHaF6oCZPtuPAf3D8M5JbhtPhTRPZyTPnQOTlpIbCvmPL0Mbk2oRymqp21gHvhnrd2UVyGhGYxDyKeZo7kMniHov5rgVTHY8GJk6MD55ZTsgExI4OHbbKLVYydStdzoBmvQmqogOkJoHEi2kNFr9mp9d6Px7uSdb3OtHWOBxtnwBBdPxDk0LlHdbs8qTwSBA53iC3S3qjJcHsm3y3Kz8Y7ukLZWEKebln15Xs7pmH4EXieC7snKpybQLJ4SJ8dLnBEjTSyU8PuwCB; YSPCD=dmz; YSITEID=4; FormAssist_1tag=view; FormAssist_cookie=jfr/20181109171257/20190511/171105-898; __bvr_customer={%22associated%22:true}; __bvr_session_activity={%22cart%22:true}; companyec_session=jpPgYQvU93pVAT2cEu4RBWdyFk9IvTW8Q8Q3opRo5uoOirAtQHNXKNHHAcaRYrCEMc1Eqaby9iFetnYRXzUsl6mp4oSUn84Qy0I1iksq2jdv9EnKLmePtDF2E1U1N5EzgBTthsc5ZaQXJJwqSIXWfhtdrFP4dBtaOUBYc1d8tSFBCe475jMufpevH9UgufxwYbX29BDipqK9NGfGPPes4iu0UAxCbmZVXNPAyUThhVgMLQtrSgxndcbUh3sytyBVv2nz7cQCzJwpQ8ZiTQWGlcBmoFIp7QNd14CC7Vj5nTV8; company_context=1.0.302.0:; JSESSIONID=0000a9oXc90MwxiJAyLP6W2UOuJ:1bt4hvbfo; CSI=xsVWkhQUDH6sW$zmKX6y2V7t41AgFiwjpsV5%3dL_CNBUpKoPWB:; SCSI=26a71a380cbc62545bc9a0845dfe87e9a29fedc284398147814f59d9d11661c5; DSCSI=fb074d8b-3f57-462b-88be-858f820054a2; ALI=xsVWkhQUDH6sW$zmKX6y2V7t41AgFiwjpsV5%3dL_CNBUpKoPWB:; CI=b87a8e28fc97c21aae168aea62c7d204; SI=3y65uv39lrrfuNiLbqLcH6HVw79c48nf9AJ27zIF5k0Y91619f; T=iiK5s9oEm00H5c79P9nP7kM4KnsFE7szv8OY2LP89y7L1omJaj; BUI=uS4:6FcWQX@Wu3-Mss@Q6ml@HG*5*MW0luZu!qs6$*lT9LXwK_"')
    # # options.add_argument('Host                     ="www.daimaru-matsuzakaya.jp"')
    # # options.add_argument('Origin                   ="https://www.daimaru-matsuzakaya.jp"')
    # # options.add_argument('Referer                  ="https://www.daimaru-matsuzakaya.jp/CreditCardAdd"')
    # # options.add_argument('Upgrade-Insecure-Requests="1"')
    # # options.add_argument(
    # #     'User-Agent               ="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"')
    #
    # # driver = webdriver.Chrome(chrome_options=options) #executable_path='chromedriver.exe',
    # print('driver',driver)
    # elem = driver.find_element_by_id("off_cardNo01")
    # elem.send_keys(Keys.NUMPAD0)
    # elem.send_keys(Keys.NUMPAD0)
    # elem.send_keys(Keys.NUMPAD0)
    # elem.send_keys(Keys.NUMPAD0)
    # driver.execute_script("ecValidateDataCard(arguments[0]);", "off_cardNo01")
    #
    # elem1 = driver.find_element_by_id("off_cardNo02")
    # # elem1.send_keys("3121")
    # elem.send_keys(Keys.NUMPAD0)
    # elem.send_keys(Keys.NUMPAD0)
    # elem.send_keys(Keys.NUMPAD0)
    # elem.send_keys(Keys.NUMPAD0)
    # driver.execute_script("ecValidateDataCard(arguments[0]);", "off_cardNo02")
    # elem2 = driver.find_element_by_id("off_cardNo03")
    # # elem2.send_keys("2421")
    #
    # elem.send_keys(Keys.NUMPAD0)
    # elem.send_keys(Keys.NUMPAD0)
    # elem.send_keys(Keys.NUMPAD0)
    # elem.send_keys(Keys.NUMPAD0)
    # driver.execute_script("ecValidateDataCard(arguments[0]);", "off_cardNo03")
    # elem3 = driver.find_element_by_id("off_cardNo04")
    # # elem3.send_keys("3333")
    #
    # elem.send_keys(Keys.NUMPAD0)
    # elem.send_keys(Keys.NUMPAD0)
    # elem.send_keys(Keys.NUMPAD0)
    # elem.send_keys(Keys.NUMPAD0)
    # driver.execute_script("ecValidateDataCard(arguments[0]);", "off_cardNo04")
    # # 年月选择 LIMIT_MONTH LIMIT_YEAR
    # S1 = Select(driver.find_element_by_name('LIMIT_MONTH')).select_by_visible_text('01')
    # S2 = Select(driver.find_element_by_name('LIMIT_YEAR')).select_by_visible_text('21')
    # print('选择填写完成，休息两秒钟 提交')
    # time.sleep(2)
    # # 提交表单 //*[@id="EC_change"]/form/div[1]/a
    # # LeftMenu = driver.find_element_by_class_name("cardAddLink")
    # # ActionChains(driver).move_to_element(LeftMenu).perform()
    # # # wait =  WebDriverWait(driver, 60);
    # # # wait.until(EC.elementToBeClickable(LeftMenu))
    # # LeftMenu.click()
    # comment_icon = driver.find_element_by_class_name("cardAddLink").send_keys(Keys.ENTER)
    # print('comment_icon', comment_icon)
    # ActionChains(driver).moveToElement(comment_icon).build().perform()
    # driver.execute_script("arguments[0].scrollIntoView();", comment_icon)
    # ActionChainsDriver = ActionChains(driver).click(comment_icon)
    print('查询操作完毕！')
    # driver.find_element_by_css_selector("a.login").click()
    # # driver.maximize_window()  #将浏览器最大化显示
    # time.sleep(3)
    # driver.find_element_by_id("userName").send_keys(login_no)
    # driver.find_element_by_id("password").send_keys(login_pw)
    # driver.find_element_by_id("subButton").click()
    # time.sleep(1)
    # driver.find_element_by_css_selector("li._subscribeTab").click()
    # time.sleep(5)
    # driver.find_element_by_css_selector("a.v2_new_fav").click()


# driver = webdriver.Firefox()
def login():
    global driver, login_no, login_pw
    driver = webdriver.Chrome(executable_path='chromedriver.exe')
    driver.implicitly_wait(10)  # 隐性等待
    driver.get('https://500px.me')
    time.sleep(2)
    # driver.maximize_window()
    driver.find_element_by_css_selector("a.login").click()
    # driver.maximize_window()  #将浏览器最大化显示
    time.sleep(3)
    driver.find_element_by_id("userName").send_keys(login_no)
    driver.find_element_by_id("password").send_keys(login_pw)
    driver.find_element_by_id("subButton").click()
    time.sleep(1)
    driver.find_element_by_css_selector("li._subscribeTab").click()
    time.sleep(5)
    # driver.find_element_by_css_selector("a.v2_new_fav").click()


def doit():
    global driver, isdo, willdo, isscroll, zan_count, zhuanfa_count, liuyan_count, zan_max, liuyan_max, cn_liuyan, en_liuyan
    now_handle = driver.current_window_handle  # 获取当前窗口句柄
    main_icons = driver.find_elements_by_class_name("new_icons_maincmp")
    if isscroll > 0:
        main_icons = main_icons[isdo:]
    print("len(main_icons):", len(main_icons))
    isscroll = isscroll + 1
    for icons in main_icons:
        isdo = isdo + 1
        if isdo % 20 == 0:
            time.sleep(2)
        try:
            time.sleep(0.2)
            # driver.execute_script("arguments[0].scrollIntoView();", icons);
            time.sleep(0.2)
            button = icons.find_element_by_class_name("v2_new_fav")
            fav_class = button.get_attribute("class")
            if "hearted" not in fav_class:
                if int(zan_max) > zan_count:
                    button.click()  # 点赞
                    print("点赞")
                    zan_count = zan_count + 1
                else:
                    print("点赞已达最大额度")

            buttons = icons.find_elements_by_class_name("v2_new_zf")
            # print(buttons)
            for button in buttons:
                fav_class = button.get_attribute("class")
                if "hearted" not in fav_class:
                    if int(zhuanfa_max) > zhuanfa_count:
                        # print("点击前")
                        # # time.sleep(3)
                        # print("点击")

                        button.click()  # 转发
                        zfid = button.get_attribute("data-target")

                        print('zfid', zfid)

                        # ActionChains(driver).move_to_element(zfbut)
                        # driver.execute_script("$(arguments[0]).click()",button)
                        # button.click()
                        print("转发点击后")
                        # time.sleep(3)
                        # print(zfid)
                        # time.sleep(13)
                        dozf(driver, zfid, button)
                    else:
                        print("转发已达最大额度")

            if int(liuyan_max) > liuyan_count:
                liuyan_button = icons.find_element_by_class_name("commentTubiao")
                liuyan_button.click()  # 打开留言
                print("打开留言1")
                time.sleep(3)
                # 判断是否有俩窗口driver.window_handles
                ifgb = 0
                for handle in driver.window_handles:
                    if handle != now_handle:
                        driver.switch_to_window(handle)
                        time.sleep(1)
                        ifgb = 1
                        driver.close()  # 关闭当前窗口

                if ifgb == 1:
                    driver.switch_to_window(now_handle)
                    continue
                actors = driver.find_elements_by_class_name("actor")
                liuyan_flag = 0
                for actor in actors:
                    # print(actor)
                    # print(actor.text)
                    if actor.text == 'hjy191':
                        liuyan_flag = 1
                print("liuyan_flag:" + str(liuyan_flag))
                if liuyan_flag == 1:
                    close_but = driver.find_element_by_class_name("close")
                    close_but.click()  # 关闭本留言
                    continue
                liuyan_text = driver.find_element_by_class_name("new_comment")
                # //*[@id="user_show"]/div[12]/div/div/div[2]/div/div[3]/div[2]/div/div[2]/div/div/div[2]/a
                photographer_info = driver.find_element_by_class_name("photographer_info")
                actor_name = photographer_info.find_element_by_class_name("actor")
                # print("actor_name:"+actor_name.text)
                if contain_zh(actor_name.text):
                    liuyan_text.send_keys(cn_liuyan)
                else:
                    liuyan_text.send_keys(en_liuyan)
                print("打开留言2")
                comment_icon = driver.find_element_by_class_name("comment_icon")
                comment_icon.click()
                print("打开留言3")
                close_but = driver.find_element_by_class_name("close")
                close_but.click()  # 关闭本留言
                liuyan_count = liuyan_count + 1
            else:
                print("留言已达最大额度")
        except Exception as e:
            print('出现以下异常：')
            print ('str(Exception):\t', str(Exception))
            print ('str(e):\t\t', str(e))
            print ('repr(e):\t', repr(e))
            continue
        finally:
            print('异常后继续下一个')


            # jiahao_class = driver.find_elements_by_class_name("jiaohao")
            # print(len(jiahao_class))
            # for jiahao in jiahao_class:
            #     print(jiahao)
            #     jiahao.click()
            #     print("加号点击了")
            #     jiahao_class = driver.find_elements_by_class_name("jiaohao")
            # comfirmZf = driver.find_element_by_css_selector("comfirmZf")
            # # comfirmZf.click()
            # print("确认转发")


errcount = 0


def dozf(driver, zfid, button):
    # button.click()
    zfbut11 = driver.find_element_by_xpath('//div[@id = "' + zfid + '"]//span')
    # locator = (By.LINK_TEXT, 'lion')
    # WebDriverWait(driver, 20, 0.5).until(EC.presence_of_element_located(locator))
    ActionChains(driver).move_to_element(zfbut11).perform()
    button.click()
    if is_element_visible(driver, zfbut11) or 1 == 1:
        # ActionChains(driver).move_to_element(zfbut).perform()
        global errcount, zhuanfa_count
        # print("挪动前,3秒后点击")
        # time.sleep(3)
        # button.click()
        # ActionChains(driver).moveToElement(button).build().perform();
        # parentitem = driver.find_elements_by_xpath('//div[@id = "'+zfid+'"]//div[@class = "inside"]')
        parentitem = driver.find_element_by_xpath('//div[@id = "' + zfid + '"]//div[@class = "inside"]')
        print('parentitem', parentitem)
        # for pitem in parentitem:
        print('进入可点循环列表')
        caozk = parentitem
        itemList = caozk.find_elements_by_xpath('//div[@class = "jiaohao"][not(contains(@class, "hasDone"))]')

        # itemList = driver.find_elements_by_xpath('//div[@id = "'+zfid+'"]//div[@class = "jiaohao"][not(contains(@class, "hasDone"))]')
        # webuiPopover60 > div.webui-popover-inner > div > div > div > div > div.inside > div:nth-child(1) > div.jiaohao
        print(len(itemList))
        if len(itemList) < 4:
            zfbut = driver.find_element_by_xpath('//div[@id = "' + zfid + '"]//span')
            # ActionChains(driver).move_to_element(zfbut).perform()
            zfbut.click()

            zhuanfa_count = zhuanfa_count + 1
            return True
        else:
            print(len(itemList))
            i = 1
            jiahao = itemList[len(itemList) - 1]
            # ActionChains(driver).move_to_element(jiahao).perform()

            # driver.execute_script("arguments[0].scrollIntoView();", jiahao)  # 拖动到可见的元素去
            # ActionChains(driver).move_to_element(jiahao).click()
            # print("点击了前,10秒后点击")
            # time.sleep(10)
            # the_element = EC.visibility_of_element_located(jiahao)
            # assert the_element(driver)
            print("1秒后准备加号点击了")
            # button.click()
            time.sleep(0.1)
            # if is_element_visible(driver, jiahao):
            jiahao.click()
            print("1秒后准备加号点击了")
            time.sleep(1)
            zfbut = driver.find_element_by_xpath('//div[@id = "' + zfid + '"]//span')
            print('zfbut')
            # ActionChains(driver).move_to_element(zfbut).perform()
            zfbut.click()
            zhuanfa_count = zhuanfa_count + 1
            return True
            # else:
            #     print("jiahao不可见等5秒")
            #     time.sleep(5)
            #     button.click()
            #     print("jiahao不可见点击后等三秒")
            #     time.sleep(3)
            #     zfbut1 = driver.find_element_by_xpath('//div[@id = "' + zfid + '"]//span')
            #     ActionChains(driver).move_to_element(zfbut1).perform()
            #     continue
            #     # ActionChains(driver).move_to_element(jiahao).perform()
            #     # jiahao.click()

            # try:
            #     print("加号点击了")
            # except Exception as e:
            #     errcount = errcount + 1
            #     print('异常次数超过三次:\t', errcount)
            #     # if errcount > 3:
            #     #     print('异常次数超过三次:\t', errcount)
            #     #     errcount = 0
            #     #     return True
            #
            #     print ('str(Exception):\t', str(Exception))
            #     print ('str(e):\t\t', str(e))
            #     print ('repr(e):\t', repr(e))
            #     # print ('e.message:\t', e.message)
            #     # button.click()
            #     # zfbut1 = driver.find_element_by_xpath('//div[@id = "' + zfid + '"]//span')
            #     # ActionChains(driver).move_to_element(zfbut1).perform()
            #     # if 'element not visible' in str(e) and errcount >5:
            #     #     errcount = 0
            #     #     print('元素找不到js操作一次:\t')
            #     #     js = 'document.getElementsByClassName("jiaohao")[0].click()'
            #     #     driver.execute_script(js)
            #     #     zfbut = driver.find_element_by_xpath('//div[@id = "' + zfid + '"]//span')
            #     #     ActionChains(driver).move_to_element(zfbut).perform()
            #     #     if is_element_visible(driver, zfbut):
            #     #         zfbut.click()
            #     #     else:
            #     #         button.click()
            #     #         zfbut = driver.find_element_by_xpath('//div[@id = "' + zfid + '"]//span')
            #     #         ActionChains(driver).move_to_element(zfbut).perform()
            #     #         zfbut = driver.find_element_by_xpath('//div[@id = "' + zfid + '"]//span')
            #     #         zfbut.click()
            #     #     zhuanfa_count = zhuanfa_count + 1
            #     #     return True
            #     # driver.execute_script("window.scrollTo(0,document.body.scrollHeight+document.body.clentHeight+20)")
            #     # continue
            # # button.click()
            # # time.sleep(10)
            # # jiahao.click()
            # print("加号点击了")
        # time.sleep(0.3)
        # dozf(driver,zfid,button)
    else:
        button.click()
        print('button点击后')
        time.sleep(3)
        zfbut = driver.find_element_by_xpath('//div[@id = "' + zfid + '"]//div[@class = "jiaohao"]')
        print("zfbut.click() is_element_visible(driver,zfbut)", is_element_visible(driver, zfbut))
        zfbut.click()
        dozf(driver, zfid, button)


def is_element_visible(driver, element):
    driver = driver
    try:
        the_element = EC.visibility_of_element_located(element)
        assert the_element(driver)
        flag = True
    except:
        flag = False
    return flag


def ifcomment(driver, nich):
    button1s = driver.find_elements_by_class_name("actor")
    for button in button1s:
        fav_class = button.get_attribute("href")
        if nich in fav_class:
            return False
    return True


# #评论
# buttons = driver.find_elements_by_class_name("commentTubiao")
# for button in buttons:
#     # print(button)
#     fav_class = button.get_attribute("class")
#     # print(fav_class)
#     if "notisGroup" not in fav_class:
#         print("单击评论")
#         button.click()  # 评论
#         time.sleep(1)
#         if ifcomment(driver,"hjy191"):
#             print("评论")
#         driver.find_element_by_css_selector("div.close").click()
#     time.sleep(1)

'''
print (len(buttons))
driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")
time.sleep(1)
buttons = driver.find_elements_by_class_name("v2_new_fav")
print (len(buttons))
'''

import threading


def fun():
    th = threading.Thread(target=mylogin, args=())
    th.setDaemon(True)  # 守护线程
    th.start()

def gofun():
    th = threading.Thread(target=getdata, args=())
    th.setDaemon(True)  # 守护线程
    th.start()

def openurlfun():
    th = threading.Thread(target=openurl, args=())
    th.setDaemon(True)  # 守护线程
    th.start()




def dopx():
    login()
    while True:
        doit()
        try:
            driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")
        except ValueError:
            print('str(Exception):\t')
        finally:
            time.sleep(5)


root = Tk()
label1 = Label(root, text='0')
label2 = Label(root, text='0')
label3 = Label(root, text='0')


def threadGetCount():
    global label1
    while (True):
        label1['text'] = '累计点赞数:' + str(getPrice())
        label2['text'] = '累计转发数:' + str(getZhuanfa())
        label3['text'] = '累计留言数:' + str(getLiuyan())
        time.sleep(1)


def getPrice():
    global zan_count
    return zan_count


def getZhuanfa():
    global zhuanfa_count
    return zhuanfa_count


def getLiuyan():
    global liuyan_count
    return liuyan_count

# number = StringVar()
# driver.quit()
if __name__ == '__main__':
    import datetime

    # global number
    # root.maxsize(600, 400)
    root.minsize(300, 240)
    end_date = datetime.datetime.strptime("2099-5-16", "%Y-%m-%d")
    datetimenowTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')  # 现在
    begin_date = datetime.datetime.strptime(datetimenowTime, "%Y-%m-%d %H:%M:%S")
    print(end_date)
    print(datetimenowTime)
    print(begin_date)
    if begin_date < end_date:
        print('还能用')
        root.title(u"daimaru批量添加账号")
        label = Label(root, fg='green')
        label['text'] = u'正式版'
        label.pack()
        Button(root, text='获取cookie方法', command=openurlfun).pack()
        # Button(root, text='批量添加', command=fun).pack()
        # Button(root, text='导出结果', command=fun).pack()
        # label1.pack()
        # label2.pack()
        # label3.pack()
        #
        frame = Frame(root)
        frame.pack()
        lab1 = Label(frame, text="cookie:")
        lab1.grid(row=0, column=0, sticky=W)
        ent1 = Entry(frame)
        ent1.grid(row=0, column=1, sticky=W)
        ent1.insert(10, zan_max)
        lab2 = Label(frame, text="选项:")
        lab2.grid(row=1, column=0, sticky=W)
        number = StringVar()
        numberChosen = ttk.Combobox(frame, width=12, textvariable=number)
        numberChosen['values'] = ("VISAカード", "マスターカード", "JCBカード", "アメックスカード")  # 设置下拉列表的值
        numberChosen.grid(row=1, column=1, sticky=W)
        # numberChosen.pack()  # 设置其在界面中出现的位置  column代表列   row 代表行
        numberChosen.current(0)
        # 创建一个下拉列表

        Button(root, text='启动浏览器执行', command=fun).pack()
        Button(root, text='手动导出数据', command=sav).pack()

        # Button(root, text='继续执行数据', command=gofun).pack()

        # lab2 = Label(frame, text="转发数限额:")
        # lab2.grid(row=1, column=0)
        # ent2 = Entry(frame)
        # ent2.insert(10, zhuanfa_max)
        # ent2.grid(row=1, column=1, sticky=W)
        # lab3 = Label(frame, text="留言数限额:")
        # lab3.grid(row=2, column=0)
        # ent3 = Entry(frame)
        # ent3.insert(10, liuyan_max)
        # ent3.grid(row=2, column=1, sticky=W)
        # lab4 = Label(frame, text="中文留言内容:")
        # lab4.grid(row=3, column=0)
        # ent4 = Entry(frame)
        # ent4.insert(10, cn_liuyan)
        # ent4.grid(row=3, column=1, sticky=W)
        # lab5 = Label(frame, text="英文留言内容:")
        # lab5.grid(row=4, column=0)
        # ent5 = Entry(frame)
        # ent5.insert(10, en_liuyan)
        # ent5.grid(row=4, column=1, sticky=W)
        # lab6 = Label(frame, text="登录手机号:")
        # lab6.grid(row=5, column=0)
        # ent6 = Entry(frame)
        # ent6.insert(10, login_no)
        # ent6.grid(row=5, column=1, sticky=W)
        # lab7 = Label(frame, text="登录密码:")
        # lab7.grid(row=6, column=0)
        # ent7 = Entry(frame, show='*')
        # ent7.insert(10, login_pw)
        # ent7.grid(row=6, column=1, sticky=W)


        # def Submit():
        #     global liuyan_max, zan_max, zhuanfa_max, cn_liuyan, en_liuyan, login_no, login_pw
        #     zan_max = ent1.get()
        #     zhuanfa_max = ent2.get()
        #     liuyan_max = ent3.get()
        #     cn_liuyan = ent4.get()
        #     en_liuyan = ent5.get()
        #     login_no = ent6.get()
        #     login_pw = ent7.get()
        #
        #
        # button = Button(frame, text="保存", command=Submit)
        # button.grid(row=7, column=1, sticky=E)

        center(root)
        t = threading.Thread(target=threadGetCount, args=(), name='thread-refresh')
        t.setDaemon(True)
        t.start()
        root.mainloop()
        # dopx()
    else:
        print('不能用')
        from tkinter import *

        root.title("提醒")
        label = Label(root)
        label['text'] = u'试用期已过，请联系 guocdfeifei@163.com 获取正式版'
        label.pack()
        center(root)
        root.mainloop()

